package com.scfire.job

import java.text.DateFormat
import java.text.SimpleDateFormat

import com.mongodb.BasicDBObject
import com.mongodb.DBCollection
import com.mongodb.DBObject
import com.scfire.message.SystemMessage
import com.scfire.project.Project
import com.scfire.security.Member
import com.scfire.util.SCFIREConstants
import com.scfire.weixin.WeiXinConstants


/** 
 * Copyright 2015 Shudao Info Tech Co. Ltd.  All rights reserved.
 * @author lhzeng
 * @email zenglh@haoshudao.com
 * @date 2015年9月7日 上午11:26:44 
 * @version V1.0
 */


/**
 * 
 *核查火堆项目是否已过期定时任务Job
 *
 */
class CheckProjectJob {
	def mongo
	def grailsApplication
	def weiXinService
	
	//设置定时器
	static triggers = {
		//定时器任务，每天凌晨0:00跑一次
		cron name:'CheckProjectJob', startDelay:10000, cronExpression: '0 0 0 * * ?'		
	 }
	
	//代码执行区
	def execute() {
		println "=========Start Check Project Job Run!========="+new Date()
		
		List<Project> projects = Project.findAllByVerified(SCFIREConstants.PROJECT_APPROVE_PASS)
		def db = mongo.getDB(grailsApplication.config.grails.mongo.databaseName)
		DBCollection projectCollection = db.getCollection("project")
		Map<String, String> donateUsersOpenid = new HashMap<String, String>()
		Date  date = new Date();
		DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm");
		def members = Member.findAllByPushFlag(true);
		for(Member member2:members){
			donateUsersOpenid.put(member2?.openid , member2?.nickname)
		}
		for(Project project:projects){
			//判断项目是否已过期
			Date curDate = new Date()
			if(curDate>project.endDate){
				//更新项目状态
				if(project.donateTimelimit < 0){//特殊项目不过期的
					
				}
				else{
					project.verified = SCFIREConstants.PROJECT_APPROVE_EXPIRED
					DBObject queryCondition= new BasicDBObject()
					queryCondition.put("_id",project.id)
					BasicDBObject updateParameter =new BasicDBObject().append("\$set",new BasicDBObject().append("verified", project.verified)
						)
					projectCollection.update(queryCondition, updateParameter,true,true)
					def member = Member.findById(project.member)
					weiXinService.sendMassTemplateStatus2(WeiXinConstants.service_id, donateUsersOpenid, "您好,"+member.nickname+"的项目《"+project.name+"》，已经过期！", fmt.format(date), "项目过期", "项目过期", "成功" , WeiXinConstants.server+"/project/projectDetail?projectid="+project?.id)
					SystemMessage systemMessage = new SystemMessage()
					systemMessage.message = SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_FAILURE_FRONT+project.name+SCFIREConstants.SYSTEM_MESSAGE_PROJECT_FUND_FAILURE_BACK
					systemMessage.date = new Date()
					systemMessage.member = project.member
					systemMessage.save flush:true
					println "project "+project.name+" has expired."
				}
				//project.save flush:true
				//保存系统通知消息
				
				
				
			}
		}
		
		println "=========End  Check Project Job Run!========="+new Date()
	}

}
 